#include <fstream>
#include <iostream>
#include <ext/hash_set>
#include "u1.h"

/*
 * Zero out all entries in a similarity matrix that don't have their movie id 
 * in a given list. Note that the Netflix movie ids start at 1 (not zero); so
 * S'(i,j) = S(i,j) if i and j in the list, for i, j = 1, 2, ..., # of movies
 *           0, otherwise
 *
 * This is used for comparing similarity matrices that have different sets of
 * movies identified.
 *
 * Takes one argument: the name of a list of ids, separated by whitespace.
 * See for example big.movies.ids.
 * Takes the source similarity matrix (S) on standard in.
 * Outputs similarity matrix (S') on standard out.
 */
using namespace __gnu_cxx;
using namespace std;

int main(int argc, char *argv[]) {
  if (argc != 2) {
    cerr<<"See comments for usage."<<endl;
    exit(EXIT_FAILURE);
  }

  /* Read netflix movie ids from file. */
  TRACE<<"Reading movie ids from "<<argv[1]<<"."<<endl;
  ifstream is(argv[1]);
  hash_set<int> movie_ids;
  while(is.good()) {
    int movie_id;
    is >> movie_id;
    if (is.good()) {
      movie_ids.insert(movie_id);
    }
  }
  TRACE<<"Got "<<movie_ids.size()<<" movie ids."<<endl;

  /* Read and write similarity files. */ 
  long count_all = 0;
  long count_kept = 0;
  for (unsigned int i = 1; i <= NUM_MOVIES; ++i) {
    for (unsigned int j = 1; j <= NUM_MOVIES; ++j) {
      double entry;
      cin >> entry;
      if (!cin.good()) {
        cerr<<"Input ended prematurely after "<<count_all<<" entries."<<endl;
        exit(EXIT_FAILURE);
      }
      ++count_all;
      if (movie_ids.count(i) > 0 && movie_ids.count(j) > 0) {
        cout<<entry<<" ";
        ++count_kept;
      } else {
        cout<<"0 ";
      }
    }
    cout<<endl;
  }
  TRACE<<"Kept "<<count_kept<<" of "<<count_all<<" entries."<<endl;

  return 0;
}


/*
* Copyright (c) 2009 John Lees-Miller
* 
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* 
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/

